package com.ztsoft.user.service.project.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztsoft.user.common.exception.CustomException;
import com.ztsoft.user.mapper.project.AnswerQuoteMapper;
import com.ztsoft.user.pojo.entity.project.AnswerQuote;
import com.ztsoft.user.pojo.entity.project.UserQuote;
import com.ztsoft.user.pojo.vo.PageData;
import com.ztsoft.user.pojo.vo.PageInfo;
import com.ztsoft.user.pojo.vo.project.AnswerQuoteVo;
import com.ztsoft.user.service.project.AnswerQuoteService;
import com.ztsoft.user.service.project.UserQuoteService;
import com.ztsoft.user.utils.AnswerQuoteListener;
import com.ztsoft.user.utils.FieldsUtils;
import com.ztsoft.user.utils.Result;
import com.ztsoft.user.utils.UploadFilesUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AnswerQuoteServiceImpl extends ServiceImpl<AnswerQuoteMapper, AnswerQuote> implements AnswerQuoteService {

    @Value("${file.dataExcelFile}")
    private String dataExcelFile;

    @Resource
    private UserQuoteService userQuoteService;

    @Override
    public Result<Object> parseUpLoadFile(String pid, MultipartFile fileList) {
//        List<String> fileNames = UploadFilesUtils.uploadFiles(fileList);
//        for (String fileName : fileNames) {
//            String filePath = dataExcelFile + fileName;
//            ExcelReader excelReader = EasyExcelFactory.read(filePath, AnswerQuoteVo.class, new AnswerQuoteListener(this, pid)).headRowNumber(2).build();
//            ReadSheet sheet = EasyExcelFactory.readSheet(0).build();
//            excelReader.read(sheet);
//            excelReader.finish();
//        }
//        return Result.success();

        List<AnswerQuote> list = new ArrayList<>();
        // 监听器，用于处理读取到的每一行数据
        AnalysisEventListener<AnswerQuote> listener = new AnalysisEventListener<AnswerQuote>() {
            @Override
            public void invoke(AnswerQuote file, AnalysisContext analysisContext) {
                file.setPid(pid);
                list.add(file);
            }
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                saveBatch(list);
                // 所有数据解析完毕后的回调
                System.out.println("所有数据解析完成");
            }
        };
        // 使用EasyExcel读取Excel文件
        try {
            EasyExcel.read(fileList.getInputStream(), AnswerQuote.class, listener).headRowNumber(2).sheet().doRead();
            return Result.success("上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            // ("上传失败,请联系管理员")
            return Result.error();
            // 异常处理
        }
    }

    @Override
    public Result<Object> querySubcontractedAll(Integer currentPage, Integer pageSize,
                                                String pid, String companyName, String projectUnit,
                                                String subcontract, String subcontracted, String packageName) {
        QueryWrapper<AnswerQuote> answerQuoteQueryWrapper = new QueryWrapper<>();
        answerQuoteQueryWrapper.like(ObjectUtil.isNotNull(companyName),"company_name", companyName);
        answerQuoteQueryWrapper.like(ObjectUtil.isNotNull(projectUnit),"project_unit", projectUnit);
        answerQuoteQueryWrapper.like(ObjectUtil.isNotNull(subcontract),"subcontract", subcontract);
        answerQuoteQueryWrapper.like(ObjectUtil.isNotNull(subcontracted),"subcontracted", subcontracted);
        answerQuoteQueryWrapper.eq(ObjectUtil.isNotNull(packageName),"package_name", packageName);
        answerQuoteQueryWrapper.eq("pid", pid).orderByAsc("subcontract","package_name");
        Page<AnswerQuote> page = new Page<>(currentPage, pageSize);
        Page<AnswerQuote> answerQuotePage = page(page, answerQuoteQueryWrapper);
        List<AnswerQuote> answerQuoteList = answerQuotePage.getRecords();

        // TODO 真的是傻逼代码，换成动态表格有什么意义？
        //  一点数据就卡的要死，还一个一个转换。又没能力写公共方法出来。蠢得要死！！！
        // 把实体字段换成动态表格标准
        List<Map<String, Object>> result = getAnswerQuoteResultMap(answerQuoteList);

        return Result.success(new PageData(result, new PageInfo(pageSize, currentPage, (int) answerQuotePage.getTotal())));
    }

    @Override
    public Result<Object> querySubcontractedTree(String pid) {
        List<Map<String, Object>> list = new ArrayList<>();

        List<AnswerQuote> answers = list(new QueryWrapper<AnswerQuote>().select("distinct subcontracted ,subcontract").eq("pid", pid).orderByAsc("subcontract"));
        for (AnswerQuote answer : answers) {
            Map<String, Object> map = new HashMap<>();
            // 取数字
            String num = answer.getSubcontract().substring(answer.getSubcontract().length() - 3);
            String subcontracted = num + "-" + answer.getSubcontracted();
            map.put("label", subcontracted);

            List<Map<String, Object>> childrenLabel = new ArrayList<>();
            List<String> companyNames = new ArrayList<>();

            list(new QueryWrapper<>(answer).select("DISTINCT package_name").eq("pid", pid).orderByAsc("package_name")).forEach(s -> companyNames.add(s.getPackageName()));

            for (String companyName : companyNames) {
                Map<String, Object> map2 = new HashMap<>();
                map2.put("label", companyName);
                childrenLabel.add(map2);
            }
            map.put("children", childrenLabel);
            list.add(map);
        }

        return Result.success(list);
    }

    @Override
    public Result<Object> updateAnswerQuote(AnswerQuote answerQuote) {
        if (updateById(answerQuote)) {
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result<Object> queryAnswerQuoteTree(String pid, String userId) {
        List<UserQuote> userQuoteList = userQuoteService.list(new QueryWrapper<UserQuote>().eq("user_id", userId));
        List<String> answerQuoteIds = new ArrayList<>();
        userQuoteList.forEach(userQuote -> answerQuoteIds.add(userQuote.getQuoteId()));

        // 查找原始树
        List<Map<String, Object>> waitForDistributionTree = new ArrayList<>();
        QueryWrapper<AnswerQuote> answerQuoteQueryWrapper = new QueryWrapper<>();
        answerQuoteQueryWrapper.select("distinct subcontracted, subcontract").eq("pid", pid);

        if (!CollectionUtils.isEmpty(answerQuoteIds)) {
            answerQuoteQueryWrapper.notIn("id", answerQuoteIds);
        }

        answerQuoteQueryWrapper.orderByAsc("subcontract");
        List<AnswerQuote> answerQuoteFatherList = list(answerQuoteQueryWrapper);
        for (AnswerQuote answer : answerQuoteFatherList) {
            Map<String, Object> map = new HashMap<>();
            // 取数字
            String num = answer.getSubcontract().substring(answer.getSubcontract().length() - 3);
            String subcontracted = num + "-" + answer.getSubcontracted();
            map.put("id", UUID.fastUUID().toString());
            map.put("label", subcontracted);

            List<Map<String, Object>> childrenLabel = new ArrayList<>();

            QueryWrapper<AnswerQuote> quoteQueryWrapper = new QueryWrapper<>(answer);
            quoteQueryWrapper.select("DISTINCT id, package_name")
                    .eq("pid", pid);
            if (!CollectionUtils.isEmpty(answerQuoteIds)) {
                quoteQueryWrapper.notIn("id", answerQuoteIds);
            }
            quoteQueryWrapper.orderByAsc("package_name");
            List<AnswerQuote> answerQuoteTreeChildList = new ArrayList<>(list(quoteQueryWrapper));

            for (AnswerQuote answerQuote : answerQuoteTreeChildList) {
                Map<String, Object> map2 = new HashMap<>();
                map2.put("id", answerQuote.getId());
                map2.put("label", answerQuote.getPackageName());
                childrenLabel.add(map2);
            }
            map.put("children", childrenLabel);
            waitForDistributionTree.add(map);
        }

        // 查找也存在关联树
        List<Map<String, Object>> allocatedTree = new ArrayList<>();
        if (!CollectionUtils.isEmpty(answerQuoteIds)) {
            List<AnswerQuote> answerQuoteAllocatedFatherList = list(new QueryWrapper<AnswerQuote>().select("distinct subcontracted, subcontract").eq("pid", pid).in("id", answerQuoteIds).orderByAsc("subcontract"));
            for (AnswerQuote answer : answerQuoteAllocatedFatherList) {
                Map<String, Object> map = new HashMap<>();
                // 取数字
                String num = answer.getSubcontract().substring(answer.getSubcontract().length() - 3);
                String subcontracted = num + "-" + answer.getSubcontracted();
                map.put("id", UUID.fastUUID().toString());
                map.put("label", subcontracted);

                List<Map<String, Object>> childrenLabel = new ArrayList<>();

                List<AnswerQuote> answerQuoteTreeChildList = new ArrayList<>(list(new QueryWrapper<>(answer).select("DISTINCT id,package_name")
                        .eq("pid", pid).in("id", answerQuoteIds)
                        .orderByAsc("package_name")));

                for (AnswerQuote answerQuote : answerQuoteTreeChildList) {
                    Map<String, Object> map2 = new HashMap<>();
                    map2.put("id", answerQuote.getId());
                    map2.put("label", answerQuote.getPackageName());
                    childrenLabel.add(map2);
                }
                map.put("children", childrenLabel);
                allocatedTree.add(map);
            }
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("waitForDistributionTree", waitForDistributionTree);
        resultMap.put("allocatedTree", allocatedTree);

        return Result.success(resultMap);
    }

    /**
     * 把实体字段换成动态表格标准
     */
    private List<Map<String, Object>> getAnswerQuoteResultMap(List<AnswerQuote> answerQuoteList) {
        // 把实体字段换成动态表格标准
        List<Map<String, Object>> result = new ArrayList<>();
        for (AnswerQuote answerQuote : answerQuoteList) {
            Map<String, Object> map = new HashMap<>();
            Field[] fields = answerQuote.getClass().getDeclaredFields();
            for (Field field : fields) {
                try {
                    // 这个是，有的字段是用private修饰的 将他设置为可读
                    field.setAccessible(true);
                    String fieldsName = "t_answer_quote_" + FieldsUtils.humpToUnderline(field.getName());
                    Object fieldsValue = field.get(answerQuote);
                    map.put(fieldsName, fieldsValue);
                } catch (Exception e) {
                    throw new CustomException(e);
                }
            }
            result.add(map);
        }
        return result;
    }

}